package dk.pun.aot.client.presenter;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasWidgets;

import dk.pun.aot.client.AlphaOmegaToolsServiceAsync;
import dk.pun.aot.client.dice.DiceRoll;
import dk.pun.aot.client.event.CoreQualityUpdatedEvent;
import dk.pun.aot.client.event.DiceRolledEvent;
import dk.pun.aot.client.event.SkillUpdatedEvent;
import dk.pun.aot.client.view.ViewCharacterView;
import dk.pun.aot.client.widget.NoCharacterSelectedPanel;
import dk.pun.aot.shared.character.CharacterData;
import dk.pun.aot.shared.character.QualityType;
import dk.pun.aot.shared.character.SkillType;
import dk.pun.aot.shared.user.UserData;

public class ViewCharacterPresenter implements Presenter, dk.pun.aot.client.view.ViewCharacterView.Presenter {

	private UserData userData;
	private AlphaOmegaToolsServiceAsync rpcService;
	private HandlerManager eventBus;
	private ViewCharacterView view;
	private NoCharacterSelectedPanel noCharacterSelectedPanel;
	private CharacterData characterData;

	public ViewCharacterPresenter(UserData userData,
			AlphaOmegaToolsServiceAsync rpcService,
			HandlerManager eventBus,
			ViewCharacterView view) {
		this.userData = userData;
		this.rpcService = rpcService;
		this.eventBus = eventBus;
		this.view = view;
		this.noCharacterSelectedPanel = new NoCharacterSelectedPanel();
		this.view.setPresenter(this);
	}
	
	@Override
	public void onCoreQualityUpdated(QualityType type, int score) {
		this.rpcService.updateCharacterData(characterData, new AsyncCallback<Void>() {

			@Override
			public void onFailure(Throwable caught) {
				GWT.log("Failed to update character data: ", caught);
			}

			@Override
			public void onSuccess(Void result) {
			}
		});
		this.eventBus.fireEvent(new CoreQualityUpdatedEvent(type, score));
	}

	@Override
	public void onSkillUpdated(SkillType type, int rank) {
		this.eventBus.fireEvent(new SkillUpdatedEvent(type, rank));
	}

	@Override
	public void onDiceRolled(DiceRoll diceRoll) {
		this.eventBus.fireEvent(new DiceRolledEvent(diceRoll));		
	}

	@Override
	public void go(final HasWidgets container) {
		container.clear();
		
		if (this.userData.getSelectedCharacterId() != null) {
			this.rpcService.getCharacterData(this.userData.getSelectedCharacterId().getKey(), new AsyncCallback<CharacterData>() {

				@Override
				public void onFailure(Throwable caught) {
					GWT.log("Failed to get character data; ", caught);
				}

				@Override
				public void onSuccess(CharacterData result) {
					view.setCharacterData(result);
					characterData = result;
					container.add(view.asWidget());
				}
			});
		} else {
			container.add(noCharacterSelectedPanel.asWidget());
		}
	}
}
